﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LiveResults;
using LiveResults.Model;

namespace LiveResults
{
    public partial class FrmOEMonitor : FrmMonitor
    {
        EventSoftwareOE softOE;
        public FrmOEMonitor(EventSoftwareOE soft, MainApp.logDelegate logger) : base(soft,logger)
        {
            InitializeComponent();
            softOE = soft;
            
            m_Parser = new OEParser();
            m_Parser.OnLogMessage += new MainApp.logDelegate(m_Parser_OnLogMessage);

            Text = "OE Monitor :: " + soft.Version;
            fileSystemWatcher1.Filter = "*" + softOE.FileExt;
            fileSystemWatcher1.Path = softOE.Directory;
            fileSystemWatcher1.SynchronizingObject = this;
            
            fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler(fileSystemWatcher1_Changed);
            fileSystemWatcher1.Created += new System.IO.FileSystemEventHandler(fileSystemWatcher1_Changed);
            fileSystemWatcher1.NotifyFilter = System.IO.NotifyFilters.LastWrite;
            fileSystemWatcher1.EnableRaisingEvents = true;
            logger("Started monitoring " + softOE.Directory + "..");
            lblCurrentlyMonitoring.Text = "Monitoring " + softOE.Directory + " for changes (filter: " + "*" + softOE.FileExt + ")";
        }

        void m_Parser_OnLogMessage(string msg)
        {
            m_Logger(msg);
        }

        OEParser m_Parser;
        void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
            if (e.ChangeType == System.IO.WatcherChangeTypes.Changed || e.ChangeType == System.IO.WatcherChangeTypes.Created)
            {
                if (System.IO.File.Exists(e.FullPath))
                {
                    m_Logger("Processing " + e.Name);
                    if (softOE.FileExt == ".xml")
                    {
                        Dictionary<string, EventClass> classes = m_Parser.ParseIOFXmlFile(e.FullPath);
                        if (classes != null)
                        {
                            foreach (KeyValuePair<string, EventClass> kvp in classes)
                            {
                                m_ModelEvent.MergeAndUpdate(kvp.Value);
                            }
                        }
                    }
                }
            }
        }
    }
}
